package com.polaris.live.ui.login

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.polaris.live.R
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.event.EventStringMessage
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ImmersionBarBuilder
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.TrackEventConst
import com.polaris.live.constant.TrackEventConst.EVENT_NEXT_UC
import com.polaris.live.databinding.ActivityPhoneNumberBinding
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.manager.AssetsConfigManager
import com.polaris.live.resp.back_resp.AreaCodeResp
import com.polaris.live.ui.login.verify.InputPasswordActivity
import com.polaris.live.ui.login.verify.SetPasswordActivity
import com.polaris.live.ui.login.verify.VerifyActivity
import com.polaris.live.utils.AutoSeparateTextWatcher
import com.polaris.live.utils.TrackHelper
import com.polaris.live.viewmodel.login.PhoneNumberModel
import com.polaris.live.widget.country.countryIcons
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 手机号验证
 *
 * @author Created by 半仙 on 2023/8/9/009 13:59
 */
class PhoneNumberActivity : BaseGoogleLoginActivity<PhoneNumberModel, ActivityPhoneNumberBinding>() {

    private var mCountryCode = ""

    override fun ImmersionBarBuilder.buildImmersionBar() {
        setTitleBar(mBinding.bvTitle)
        setStatusBarDarkFont(false)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        EventBus.getDefault().register(this)

        initListener()
        initObserve()

        val pair = CacheUtil.getLastPhoneNumber()
        if (pair != null) {
            val (areaCode, phoneNumber) = pair
            mBinding.phoneNumberEdit.setText(phoneNumber)
            mBinding.phoneNumberClear.visibility = View.VISIBLE
            mBinding.loginButton.alpha = 1f
            mViewModel.getCountryCodeByAreaCode(areaCode)
        }

        mViewModel.getIp()
    }

    private fun initListener() {
        val textWatcher = AutoSeparateTextWatcher(mBinding.phoneNumberEdit)
        textWatcher.setRules(intArrayOf(3, 4, 4, 4, 4, 4))
        textWatcher.separator = ' '
        mBinding.phoneNumberEdit.addTextChangedListener(textWatcher)

        textWatcher.setAddTextChanage {
            val toString = mBinding.phoneNumberEdit.text.toString()
            val trimmedStr = toString.replace("\\s+".toRegex(), "")  // 去掉所有空格

            if (trimmedStr.length < 7) {
                mBinding.loginButton.alpha = AppConst.NOTCLICK
            } else {
                mBinding.loginButton.alpha = 1.0f
            }
            if (toString.isEmpty()) {
                mBinding.phoneNumberClear.visibility = View.INVISIBLE
            } else {
                mBinding.phoneNumberClear.visibility = View.VISIBLE
            }
        }

        mBinding.loginButton.setOnSingleClickListener {
            TrackHelper.trackActivity(this, EVENT_NEXT_UC)
            val toString = mBinding.phoneNumberEdit.text.toString()
            val phoneNumber = toString.replace("\\s+".toRegex(), "")  // 去掉所有空格

            val phoneCode = mBinding.phoneAreaCode.text.toString()
            val areaCode = phoneCode.substring(1)

            if (phoneNumber.length >= 7) {
                mViewModel.isRegistered(areaCode, phoneNumber)
            }
        }
        mBinding.selectGoogleLogin.setOnSingleClickListener {
            TrackHelper.trackActivity(this, TrackEventConst.EVENT_LOGIN_GOOGLE_UC)
            gotoGoogleLogin()
        }

        mBinding.llAreaCode.setOnSingleClickListener {
            val intent = Intent(this, AreaCodeActivity::class.java)
            intent.putExtra("countryCode", mCountryCode)
            areaCodeRegister.launch(intent)
        }
        mBinding.phoneNumberClear.setOnSingleClickListener {
            mBinding.phoneNumberEdit.setText("")
        }

        mBinding.bvTitle.setOnLeftClientListener {
            TrackHelper.trackActivity(this, TrackEventConst.EVENT_RETURN_UC)
            finish()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        TrackHelper.trackActivity(this, TrackEventConst.EVENT_RETURN_UC)
        return super.onKeyDown(keyCode, event)
    }

    private fun initObserve() {
        mViewModel.ipLiveData.observe(this) {
            mCountryCode = it ?: "CA"

            if (mBinding.phoneAreaCode.text.isEmpty()) {
                val areaCodeBean = AssetsConfigManager.getAreaCode(mCountryCode)
                if (areaCodeBean != null) {
                    updateAreaCode(areaCodeBean)
                } else {
                    mViewModel.getAreaCodeByCountryCode(mCountryCode)
                }
            }
        }
        mViewModel.areaCodeLiveData.observe(this) {
            updateAreaCode(it)
        }

        mViewModel.isRegisteredLiveData.observe(this) { resultState ->
            parseState(resultState, { resp ->
                val intent = Intent()
                if (resp.registered == false) {
                    //转跳验证码
                    verifyGoogle {
                        intent.setClass(this, VerifyActivity::class.java)
                        if (it != null) {
                            intent.putExtra("googleValidate", it)
                        }
                        gotoLogin(intent)
                    }
                } else {
                    //转跳 设置密码 或者 输入密码
                    if (resp.hasPassword == false) {
                        verifyGoogle {
                            intent.setClass(this, SetPasswordActivity::class.java)
                            intent.putExtra("isLogin", true)
                            intent.putExtra("isFirstSet", true)
                            if (it != null) {
                                intent.putExtra("googleValidate", it)
                            }
                            gotoLogin(intent)
                        }
                    } else {
                        intent.setClass(this, InputPasswordActivity::class.java)
                        gotoLogin(intent)
                    }
                }
            }, {
                if (it.errCode == CommonConst.ErrorCode.SEAL_ACCOUNT || it.errCode == CommonConst.ErrorCode.SEAL_ACCOUNT_LOGIN || it.errCode == CommonConst.ErrorCode.SEAL_ACCOUNT_STOP) {
                    GlobalDialogManager.showSealAccountDialog(this, JsonUtils.toJson(it.ext))
                } else {
                    ToastGravity.showGravity(it.errorMsg)
                }
            })
        }
    }

    private fun gotoLogin(intent: Intent) {
        val toString = mBinding.phoneNumberEdit.text.toString()
        val phoneNumber = toString.replace("\\s+".toRegex(), "")  // 去掉所有空格
        val phoneCode = mBinding.phoneAreaCode.text.toString()
        val areaCode = phoneCode.substring(1)

        intent.putExtra("areaCode", areaCode)
        intent.putExtra("phoneNumber", phoneNumber)
        startActivity(intent)
    }

    private fun updateAreaCode(resp: AreaCodeResp) {
        mBinding.phoneNumberImg.setImageResource(resp.countryCode?.let { countryIcons[it] }
            ?: R.color.gray)
        mBinding.phoneAreaCode.text = "+${resp.areaCode}"
    }

    private val areaCodeRegister =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val resp = result.data?.getParcelableExtra<AreaCodeResp>("areaCode")
                resp?.also { updateAreaCode(it) }
            }
        }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEventBus(event: EventStringMessage) {
        when (event.from) {
            BizEventConst.LOGIN_FINISH -> {
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}